package com.anita.member.domain.model.member;

import com.alibaba.nacos.common.utils.StringUtils;
import com.anita.member.common.exception.BusinessException;

import java.util.Objects;

/**
 * 地址值对象
 * @author qiu
 * @date 2025/10/17
 * @description
 */
public record Location (
        String province,    //省/州
        String city,        //市
        String district,    //区/县
        String street,      //街道
        String detail       //详细门牌号
){
    public Location {

        // 去空格
        province = Objects.requireNonNull(province, "省份不能为空").trim();
        city = Objects.requireNonNull(city, "城市不能为空").trim();
        district = Objects.requireNonNull(district, "区县不能为空").trim();
        street = Objects.requireNonNull(street, "街道不能为空").trim();
        detail = Objects.requireNonNull(detail, "详细地址不能为空").trim();

        if(province.isEmpty() || city.isEmpty() || district.isEmpty() || street.isEmpty() || detail.isEmpty()){
            throw new BusinessException("地址各项不能为空");
        }

        if (detail.length() > 200) {
            throw new BusinessException("详细地址不能超过200字符");
        }
    }

    public static Location of(String province, String city, String district, String street, String detail) {
        return new Location(province, city, district, street, detail);
    }

    /**
     * 合并成一行字符串，方便日志或快递面单打印
     */
    public String singleLine() {
        return province + city + district + street + detail;
    }

    /**
     * 把实体里常见的 "省 市 区 街道 详情" 整串拆成 Location
     * 分隔符：空格或逗号均可，缺省部分补空串
     */
    public static Location fromString(String address) {
        if (!StringUtils.hasText(address)) {
            throw new BusinessException("地址字符串不能为空");
        }
        // 统一逗号→空格，再按连续空格拆分
        String[] arr = address.replace(',', ' ')
                .trim()
                .split("\\s+");
        // 不足 5 段，后面补空串
        String[] defaults = {"", "", "", "", ""};
        System.arraycopy(arr, 0, defaults, 0, Math.min(arr.length, 5));
        return new Location(defaults[0], defaults[1], defaults[2], defaults[3], defaults[4]);
    }

    @Override
    public String toString() {
        return singleLine();
    }

}
